<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'

import { ConditionInit } from '@fl/api/anjutong'
import { getTemplates, sendMessage, v1MessageGroups } from '@fl/api/ums-api'
import { ElForm } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

import { MessageData } from './type'

const router = useRouter()
const { form } = reactive(new MessageData())
const selectData: any = ref([])
// 获取模版
async function getMessageTemp() {
    const param = {
        channel: form.channel,
        page: '1',
        page_size: '10',
    }
    const res = await getTemplates(param)

    selectData.value = res.items
}
const userList = ref()
// 获取会员等级
async function getConditionInit() {
    const res = await ConditionInit()
    console.log(res)
    userList.value = res
}
getConditionInit()
// 获取消息分组
let v1MessageGroupsData: any = []
async function getv1MessageGroups() {
    const param = {
        channel: form.channel,
        page: '1',
        page_size: '10',
    }
    const res = await v1MessageGroups(param)
    console.log(res)
    v1MessageGroupsData = res.items
}

// 模版id
const code = ref(null)
// 内容
// const content = ref('')
console.log(selectData)
// 模版
function tempChange(val: any) {
    console.log(val)
    const arr = val.split(']]')
    code.value = arr[0]
    form.content = arr[1]
}
// 发送渠道
async function channelChange(val: any) {
    console.log(val)
    clear()
    if (['SMS', 'WeChatApp'].includes(val))
        await getMessageTemp()
    else
        await getv1MessageGroups()
}
// 发送类型
function sendTypeChange(val: any) {
    console.log(val)

    if (val === '1')
        form.regular_time = getNowTime()
    else if (val === '2')
        form.regular_time = ''
}
// 属性
function userAttr() {
    form.receiver.member_type = ''
    form.receiver.member_tag_id_list = []
    form.receiver.member_level_list = []
}
// 获取当前时间
function getNowTime() {
    const d = new Date()
    const year = d.getFullYear()
    const month = (d.getMonth() + 1) < 10 ? `0${d.getMonth() + 1}` : (d.getMonth() + 1)
    const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate()
    const hour = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours()
    const minute = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes()
    const second = d.getSeconds() < 10 ? `0${d.getSeconds()}` : d.getSeconds()
    return `${[year, month, day].join('-')} ${[hour, minute, second].join(':')}`
}
onMounted(async () => {
    if (['SMS', 'WeChatApp'].includes(form.channel))
        await getMessageTemp()

    if (['PMSG'].includes(form.channel))
        await getv1MessageGroups()
})
// 验证
async function onSubmit(el: FormInstance | undefined) {
    if (!el)
        return
    await el.validate((v) => {
        if (v)
            saveMessage()
    })
}
// 新增
function saveMessage() {
    const param: any = {
        channel: form.channel,
        is_template: !!code.value,
        link: form.link,
        receiver: {
            is_to_all: form.selectRange === '1',
            member_level_list: form.receiver.member_level_list,
            member_tag_id_list: form.receiver.member_tag_id_list,
            member_type: form.receiver.member_type,
        },
        regular_time: form.regular_time,
        subject: form.subject,
    }
    if (form.channel === 'SMS' || form.channel === 'WeChatApp') {
        param.template_message = {
            template_code: code.value,
            variables: {
                description: form.content,
            },
        }
    }
    else {
        param.text_message = {
            content: form.content,
            group_id: v1MessageGroupsData[0].id,
        }
    }
    sendMessage(param).then((res) => {
        console.log(res)

        ElMessage.success('新增成功')
        router.push('/marketing-promotion/message-center-service/notify')
    }).catch((err) => {
        ElMessage.error(err)
    })
}
// 切换时清空
function clear() {
    form.subject = ''
    form.regular_time = ''
    form.sendType = '2'
    form.content = ''
    code.value = null
    form.template_id = ''
    form.link = ''
    form.selectRange = '1'
    form.userAttr = ''
    form.receiver.member_tag_id_list = []
    form.receiver.member_type = ''
    form.receiver.member_level_list = []
}
const messageRef = ref<FormInstance>()
const rules = reactive<FormRules<any>>({
    channel: [
        { message: '请选择发送渠道', required: true, trigger: 'blur' },
    ],
    content: [
        { message: '请输入通知内容', required: true, trigger: 'blur' },
    ],
    link: [
        { message: '请输入目标链接', required: true, trigger: 'blur' },
    ],
    subject: [
        { message: '请输入通知名称', required: true, trigger: 'blur' },
    ],
    template_id: [
        { message: '请选择模版', required: true, trigger: 'blur' },
    ],

})
</script>

<template>
    <div class="per">
        <p class="title">
            消息发送
        </p>

        <div class="con">
            <div class="main">
                <ElForm ref="messageRef"
                        :model="form"
                        :rules="rules"
                        label-width="auto"
                        style="max-width: 600px"
                >
                    <el-form-item label="发送渠道"
                                  prop="channel"
                    >
                        <el-select v-model="form.channel"
                                   @change="channelChange(form.channel)"
                        >
                            <el-option label="短信"
                                       value="SMS"
                            />

                            <!-- <el-option label="APP"
                                   value="APP"
                        /> -->

                            <el-option label="微信"
                                       value="WeChatApp"
                            />

                            <el-option label="系统消息"
                                       value="PMSG"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="发送类型">
                        <el-radio-group v-model="form.sendType"
                                        @change="sendTypeChange(form.sendType)"
                        >
                            <el-radio value="1">
                                实时
                            </el-radio>

                            <el-radio value="2">
                                定时
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="时间">
                        <el-date-picker v-model="form.regular_time"
                                        type="datetime"
                                        placeholder="时间"
                                        value-format="YYYY-MM-DD hh:mm:ss"
                                        style="width: 100%"
                                        :disabled="form.sendType === '1'"
                        />
                    </el-form-item>

                    <el-form-item v-if="form.channel === 'PMSG'"
                                  label="通知名称"
                                  prop="subject"
                    >
                        <el-input v-model="form.subject"
                                  placeholder="请输入通知名称"
                        />
                    </el-form-item>

                    <!-- <el-form-item v-else-if="form.select === '3'"
                                  label="选择账号"
                    >
                        <el-select v-model="form.select1">
                            <el-option label="选择账号"
                                       value="1"
                            />
                        </el-select>
                    </el-form-item> -->

                    <el-form-item v-if="form.channel === 'PMSG'"
                                  label="通知内容"
                                  prop="content"
                    >
                        <el-input v-model="form.content"
                                  type="textarea"
                        />
                    </el-form-item>

                    <el-form-item v-if="form.channel === 'SMS'"
                                  label="短信内容"
                    >
                        <el-input v-model="form.content"
                                  type="textarea"
                        />
                    </el-form-item>

                    <el-form-item v-if="form.channel !== 'PMSG'"
                                  label="选择模版"
                                  prop="template_id"
                    >
                        <el-select v-model="form.template_id"
                                   @change="tempChange(form.template_id)"
                        >
                            <el-option v-for="item in selectData"
                                       :key="item.template_code"
                                       :label="item.template_name"
                                       :value="`${item.template_code}]]${item.template_content}`"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="目标链接"
                                  prop="link"
                    >
                        <el-input v-model="form.link"
                                  type="text"
                                  placeholder="请输入链接"
                        />
                    </el-form-item>

                    <el-form-item label="选择范围">
                        <el-radio-group v-model="form.selectRange">
                            <el-radio value="1">
                                所有用户
                            </el-radio>

                            <el-radio value="2">
                                按属性
                            </el-radio>

                            <!-- <el-radio v-if="form.channel === 'SMS'"
                                      value="3"
                            >
                                批量导入
                            </el-radio> -->
                        </el-radio-group>

                        <!-- <span v-if="form.channel === 'SMS'"
                              class="upload"
                        >
                            <span>上传</span>

                            <span class="upload">模版下载</span>
                        </span> -->
                    </el-form-item>

                    <el-form-item label="属性">
                        <div style="display: flex;">
                            <div style="flex: 0 0 80px;">
                                <el-radio-group v-model="form.userAttr"
                                                @change="userAttr()"
                                >
                                    <el-radio value="1"
                                              class="block"
                                    >
                                        会员等级
                                    </el-radio>

                                    <el-radio value="2"
                                              class="block"
                                    >
                                        用户类型
                                    </el-radio>

                                    <el-radio value="3"
                                              class="block"
                                    >
                                        用户标签
                                    </el-radio>
                                </el-radio-group>
                            </div>

                            <div v-if="form.userAttr === '3'">
                                <el-select v-model="form.receiver.member_tag_id_list"
                                           style="width:200px"
                                           multiple
                                >
                                    <el-option v-for="item in userList.memberTagVOList"
                                               :key="item.id"
                                               :label="item.name"
                                               :value="item.id"
                                    />
                                </el-select>
                            </div>

                            <div v-else-if="form.userAttr === '2'">
                                <el-select v-model="form.receiver.member_type"
                                           style="width:200px"
                                >
                                    <el-option v-for="item in userList.memberTypeVOList"
                                               :key="item.code"
                                               :value="item.code"
                                               :label="item.name"
                                    />
                                </el-select>
                            </div>

                            <div v-else-if="form.userAttr === '1'">
                                <el-select v-model="form.receiver.member_level_list"
                                           style="width:200px"
                                           multiple
                                >
                                    <el-option v-for="item in userList.memberLevelVOList"
                                               :key="item.levelId"
                                               :value="item.levelId"
                                               :label="item.levelName"
                                    />
                                </el-select>
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item>
                        <el-button @click="router.push('/marketing-promotion/message-center-service/notify')">
                            取消
                        </el-button>

                        <el-button type="primary"
                                   @click="onSubmit(messageRef)"
                        >
                            提交
                        </el-button>
                    </el-form-item>
                </ElForm>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.per {
    background-color: #fff;
}

.title {
    font-size: 20px;
    font-weight: 600;
    padding: 10px 0 20px 40px;
}

.con {
    display: flex;
    align-items: center;
    justify-content: center;

    .main {
        // border: 1px solid red;
        width: 500px;
        height: 600px;
        padding: 20px;
    }
}

.upload {
    display: inline-block;
    margin-left: 10px;
    color: #da0004;
}

.block {
    width: 100%;
}

.foot {
    display: flex;
    align-items: center;
}
</style>
